package com.sziit.se.highconcurrency.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.sziit.se.highconcurrency.common.exception.UnAuthenticationException;
import com.sziit.se.highconcurrency.common.tool.JwtUtils;
import com.sziit.se.highconcurrency.common.entity.User;
import com.sziit.se.highconcurrency.common.service.IUserService;
import com.sziit.se.highconcurrency.common.tool.LocalUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Optional;

import static com.sziit.se.highconcurrency.common.constant.SystemConstants.SALT;

@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;
//    @Resource
//    private UserRoleService userRoleService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LocalUser.clear();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("==========>" + request.getMethod() + request.getRequestURI());
        log.info("==========>请求headers:");
        //获取请求头信息
        Enumeration<String> headerNames = request.getHeaderNames();
        //使用循环遍历请求头，并通过getHeader()方法获取一个指定名称的头字段
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info(headerName + " : " + request.getHeader(headerName));
        }
        Enumeration<String> paramNames = request.getParameterNames();
        log.info("==========>请求params:");
        while (paramNames.hasMoreElements()) {
            String name = paramNames.nextElement();
            String value = request.getParameter(name);
            log.info(name + " : " + value);
        }
        String token = request.getHeader("Authorization");
        //token为空
        if (StrUtil.isEmpty(token)) {
            throw new UnAuthenticationException();
        }
        // 解密获得username，用于和数据库进行对比

        String account = JwtUtils.getAccount(token);

        if (StrUtil.isEmpty(account)) {
            throw new UnAuthenticationException();
        }
        User user = Optional.ofNullable(userService.getById(account)).orElseThrow(UnAuthenticationException::new);
        boolean verifySuccess = JwtUtils.verify(token, account, user.getPassword());
        if (!verifySuccess) {
            log.error("token verify failed");
            throw new UnAuthenticationException();
        }
        //TODO :超级管理员鉴权，待实现
//        NeedAdmin annotation = null;
//        //判断是否需要管理员权限
//        if(handler instanceof HandlerMethod) {
//            annotation = ((HandlerMethod) handler).getMethodAnnotation(NeedAdmin.class);
//        }
//        //需要管理员权限，但是当前用户不是管理员
//        if (annotation != null && !userRoleService.isAdministrator(user.getId())) {
//            throw new UnAuthenticationException();
//        }
        log.info("==========>当前用户：" + user.getUserName());
        LocalUser.set(user);
        log.info("==========>当前用户：" + LocalUser.getUser());
        return true;
    }
}
